import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:seedfour/app/constants.dart';
import 'package:seedfour/app/views/module_order/OrderStatusHandler.dart';

import '../../../models/pay_order_list_entity.dart';
import '../../../theme.dart';
import '../../../widget/null_tip.dart';
import 'logic.dart';

class OrderPaidPage extends StatelessWidget {
  OrderPaidPage({Key? key}) : super(key: key);

  final logic = Get.find<OrderPaidLogic>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Obx(() =>
            logic.isSearching.value ? _buildSearchField() : const Text('付款')),
        bottom: TabBar(
          controller: logic.tabController,
          tabs: payOrderStatus.values.map((title) => Tab(text: title)).toList(),
        ),
        leading: IconButton(
          icon: Icon(
            Icons.arrow_back_ios,
            size: 16.w,
          ),
          onPressed: () {
            Get.back();
          },
        ),
        // 创建付款订单按钮
        actions: [
          Obx(
            () => logic.isSearching.value
                ? Container()
                : IconButton(
                    onPressed: () => {logic.onClickSearch()},
                    icon: SvgPicture.asset(
                      'assets/icons/ic_search.svg',
                      width: kIconSizeTiny,
                    ),
                  ),
          ),
          Obx(
            () => logic.isSearching.value
                ? Container()
                : IconButton(
                    onPressed: () => logic.toCreateOrder(),
                    icon: const Icon(Icons.add),
                  ),
          ),
        ],
      ),
      body: Obx(() {
        if (logic.isLoading.value) {
          return const Center(child: CircularProgressIndicator());
        } else {
          return RefreshIndicator(
            onRefresh: () async => logic.reload(),
            child: Stack(
              children: [
                ListView.builder(
                    physics: const AlwaysScrollableScrollPhysics(),
                    controller: logic.scrollController,
                    itemBuilder: _renderRow,
                    itemCount: logic.orderList.length + 2),
                if (logic.isSearching.value && !logic.isSearched.value)
                  Container(
                    width: double.maxFinite,
                    height: double.maxFinite,
                    color: const Color(0x55000000),
                  ),
              ],
            ),
          );
        }
      }),
    );
  }

  Widget _buildSearchField() {
    return Container(
      height: 40.w,
      margin: EdgeInsets.only(right: kSpaceMedium),
      child: TextField(
        autofocus: true,
        controller: logic.searchController,
        keyboardType: TextInputType.text,
        textInputAction: TextInputAction.search,
        onSubmitted: (value) => logic.onSearch(),
        onTap: () => logic.onClickSearch(),
        decoration: InputDecoration(
          prefixIcon: IconButton(
            icon: SvgPicture.asset(
              'assets/icons/ic_search.svg',
              width: kIconSizeTiny,
              height: kIconSizeTiny,
            ),
            onPressed: () => logic.onSearch(),
          ),
          suffixIcon: IconButton(
            iconSize: kIconSizeTiny,
            icon: const Icon(Icons.close),
            onPressed: () => logic.onCancelSearch(),
          ),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(kRadiusMedium),
            borderSide: const BorderSide(color: AppColor.colorBorderGrey),
          ),
          hintText: '对方户名或创建人',
          hintStyle: TextStyle(
            fontSize: kFontSizeSmall,
            color: AppColor.colorFontHint,
          ),
          contentPadding:
              EdgeInsets.symmetric(horizontal: 10.w, vertical: 10.w),
        ),
      ),
    );
  }

  Widget _buildListItem(PaidOrderInfo item) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: EdgeInsets.all(kSpaceMedium),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                item.createdAt == null
                    ? ''
                    : DateFormat('yyyy.MM.dd HH.mm').format(
                        DateTime.fromMillisecondsSinceEpoch(item.createdAt!)),
                style: TextStyle(
                  color: AppColor.colorFontBlack,
                  fontSize: kFontSizeMedium,
                  fontWeight: AppFont.fontRegular,
                ),
              ),
              Text(
                getPaidOrderStatusDesc(item),
                style: TextStyle(
                  color: switch (item.orderStatus) {
                    0 => AppColor.colorFontRed,
                    1 => AppColor.colorFontOrange,
                    3 => AppColor.colorFontGreen,
                    int() => throw UnimplementedError(),
                    null => throw UnimplementedError(),
                  },
                  fontSize: kFontSizeMedium,
                  fontWeight: AppFont.fontRegular,
                ),
              ),
            ],
          ),
        ),
        Container(color: AppColor.colorLineGrey, height: 0.5.w),
        SizedBox(height: kSpaceMedium),
        Padding(
          padding: EdgeInsets.symmetric(horizontal: kSpaceMedium),
          child: Text(
            item.title == null ? '' : item.title!.split(',').first,
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              fontSize: kFontSizeSmall,
              fontWeight: AppFont.fontRegular,
              color: AppColor.colorFontBlack,
            ),
          ),
        ),
        SizedBox(height: kSpaceMini),
        Padding(
          padding: EdgeInsets.symmetric(horizontal: kSpaceMedium),
          child: Text(
            item.orderAmountStr ?? '¥0.00',
            style: TextStyle(
              fontWeight: AppFont.fontMedium,
              fontSize: kFontSizeBig,
              color: AppColor.colorFontBlack,
            ),
          ),
        ),
        SizedBox(height: kSpaceMini),
        Container(
          margin: EdgeInsets.symmetric(horizontal: kSpaceMedium),
          padding: EdgeInsets.symmetric(horizontal: 6.w, vertical: 4.w),
          decoration: BoxDecoration(
            color: AppColor.colorTagBackground,
            borderRadius: BorderRadius.circular(kSpaceTiny),
          ),
          child: Text(item.orderRemark ?? '',
              style: TextStyle(
                color: AppColor.colorFontBlack,
                fontSize: kFontSizeTiny,
                fontWeight: AppFont.fontRegular,
                height: 1.2,
              ),
              overflow: TextOverflow.ellipsis),
        ),
        SizedBox(height: kSpaceMedium),
      ],
    );
  }

  Widget _getMoreWidget() {
    return Center(
      child: Padding(
        padding: EdgeInsets.only(bottom: kSpaceMedium),
        child: Text(
          logic.bottomTips.value,
          style: TextStyle(fontSize: kFontSizeSmall, color: Colors.grey),
        ),
      ),
    );
  }

  Widget _renderRow(BuildContext context, int index) {
    if (index == 0) {
      return _buildTotalAmount();
    } else if (index < logic.orderList.length + 1) {
      int i = index - 1;
      return Padding(
        padding: EdgeInsets.only(
            left: kSpaceMedium, right: kSpaceMedium, bottom: kSpaceMedium),
        child: ClipRRect(
          borderRadius: BorderRadius.all(Radius.circular(kSpaceSmall)),
          child: Material(
            color: Colors.white,
            child: InkWell(
              onTap: () => logic.toOrderDetail(i),
              child: _buildListItem(logic.orderList[i]),
            ),
          ),
        ),
      );
    } else if (logic.orderList.isEmpty) {
      return Column(
        children: [
          SizedBox(height: kSpaceHuge),
          const NullTip(),
        ],
      );
    } else {
      return _getMoreWidget();
    }
  }

  Widget _buildTotalAmount() {
    return Container(
      width: double.maxFinite,
      padding:
          EdgeInsets.symmetric(horizontal: kSpaceMedium, vertical: kSpaceSmall),
      margin:
          EdgeInsets.symmetric(horizontal: kSpaceSmall, vertical: kSpaceMedium),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(kSpaceSmall),
      ),
      child: Obx(
        () => Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                switch (logic.orderStatus.value) {
                  -1 => '总计金额(元)',
                  0 => '未审批金额(元)',
                  1 => '付款中金额(元)',
                  3 => '已完成金额(元)',
                  int() => throw UnimplementedError(),
                },
                style: TextStyle(
                  fontSize: kFontSizeMedium,
                  color: AppColor.colorFontBlack,
                  fontWeight: AppFont.fontRegular,
                ),
              ),
              Text(
                logic.orderListEntity.value == null ||
                        logic.orderListEntity.value!.sumAmount == null
                    ? '0.00'
                    : logic.orderListEntity.value!.sumAmount!
                        .replaceAll('¥', ''),
                style: TextStyle(
                  fontSize: kFontSizeLarge,
                  fontWeight: AppFont.fontMedium,
                  color: switch (logic.orderStatus.value) {
                    -1 => AppColor.colorFontBlack,
                    0 => AppColor.colorFontRed,
                    1 => AppColor.colorFontOrange,
                    3 => AppColor.colorFontGreen,
                    int() => throw UnimplementedError(),
                  },
                ),
              ),
            ]),
      ),
    );
  }
}
